<?php
/**
 * This class handles all the connection to sources other then the database, like youtube, last.fm and echonest
 */
class Search{
    private $keyLastFM='2e0f6a31b6598dae0585ac68964d579c';
    private $keyYoutube='AI39si4YSDe1lkU6-yY1v-oEFe992820MM85Qt0QgVqJAo-4JPy0ABXGNFTyGrDYifFMzVI-ztCk1RY1aCXkPILKw2d6NkCWKQ';
    /**
     * Empty constructor
     */
    public function Search(){
        
    }
    /**
     * Replaces all the white spaces with %20
     * @param String $input The string to be checked for white spaces
     * @return String $input with white spaces replaced by %20 
     */
    private function removeWhite($input){
        return str_replace(' ','%20',$input);
    }
    
    /**
     * Perfomaces a last.fm search 
     * @param String $searchTerms the search input
     * @param int $limit the amount of items to be returned
     * @return array consists of artistname and trackname that correspond in a way with the search terms 
     */
    public function searchSong($searchTerms,$limit=10){
        $count=0;
        $urlPart1='http://ws.audioscrobbler.com/2.0/?method=track.search&format=json';
        $urlPart2='&track='.$this->removeWhite($searchTerms);
        $url=$urlPart1.'&api_key='.$this->keyLastFM.$urlPart2;
        
        $html=file_get_contents($url,true);
        $json=json_decode($html,true);
        $out=array();
        //Check whether if $json has results
        if(isset($json['results']['trackmatches']['track']) && is_array($json['results']['trackmatches']['track'])){
            foreach($json['results']['trackmatches']['track'] as $key=>$val){
                if($count==$limit){break;}
                $count++;
                $out[$key]['track']=$val['name'];
                $out[$key]['artist']=$val['artist'];
            }
        }
        return $out;
    }

    /**
     * Makes a webservice call to youtube to get a video corresponding to the given artist name and track name
     * @param String $artistName The name of the artist
     * @param String $trackName The name of the track
     * @return String an Youtube id of a video 
     */
    public function playerLink($artistName,$trackName){
        
        $first='http://gdata.youtube.com/feeds/api/videos?q=';
        $second=str_replace(' ', '%20', $artistName." ".$trackName);
        $third='&orderby=relevance&max-results=1&format=5&alt=json';
        $url=$first.$second.$third;
        
        $html=file_get_contents($url);
        $json=json_decode($html,true);
        
        $link;
        //if the request fails or there isn't any youtube video, return null
        if(isset($json['feed']['entry'][0]['link'][0]['href'])){
            $link=$json['feed']['entry'][0]['link'][0]['href'];
        }
        else{
            return null;
        }
        
        $out='';
        //Strip the youtube id of the return value of the webservice call
        for($j=31;$j<42;$j++){
            $out.=$link[$j];
        }
        return($out);
    }

    /**
     * Retrieves artist information from last.fm and echonest
     * @param String $artistName The artist name
     * @return Artist An artist object
     */
    public function getArtistFromWeb($artistName){
        //Part1, consists of retrieving the listen count, genres and similar artists from last.fm
        $urlSetup='http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&format=json&artist=';
        $object=new Artist();
        $artist=rtrim($artistName);
        
        $artist=str_replace(' ','%20',$artist);

        $url=$urlSetup.$artist.'&api_key='.$this->keyLastFM;
        $html=file_get_contents($url,'r');
        $json=json_decode($html,true);
        if(isset($json['artist']['name'])){
            $object->setName($json['artist']['name']);
        }
        else{
            return null;
        }
        if(isset($json['artist'])){
            $object->setListeners($json['artist']['stats']['playcount']);
        }
        else{
            return null;
        }
        if(isset($json['artist']['similar']['artist'])){
            foreach($json['artist']['similar']['artist'] as $count=>$similar){
                $object->addSimilar($similar['name']);
            }
        }

        if(isset($json['artist']['tags']['tag'])){
            foreach($json['artist']['tags']['tag'] as $count=>$tag){
                $object->addGenre($tag['name']);
            }
        }
        //Part 2, consists of retrieving the active years from echonest.com
        $first='http://developer.echonest.com/api/v4/artist/years_active?api_key=N6E4NIOVYMTHNDM8J&name=';
        $artist=str_replace(' ','%20',$artistName);
        $url=$first.$artist;
        $html=  file_get_contents($url,true);
        $json=  json_decode($html,true);

        if($json['response']['status']['code']==0){
            //the default years
            $year1=2000;
            $year2=2012;
            if(isset($json['response']['artist']['years_active'][0])){
                $var=$json['response']['artist']['years_active'][0];
                $i=1;
                foreach($var as $val){
                    $temp='year'.$i;
                    $$temp=$val;
                    $i++;
                }
            }
            $object->setYearActive($year1,$year2);
        }
        return $object;
    }
    
    /**
     * Retrieves all the tracks that belong to an album
     * @param String $artistName The artist name
     * @param String $albumName The album name
     * @return array of tracks
     */
    public function getSongsFromWeb($artistName,$albumName){
        $first='http://ws.audioscrobbler.com/2.0/?method=album.getinfo&format=json&api_key=b25b959554ed76058ac220b7b2e0a026&artist=';
        $key='&api_key=2e0f6a31b6598dae0585ac68964d579c';
        $second='&album=';
        $artist=str_replace(' ','%20',$artistName);
        $album=str_replace(' ','%20',$albumName);

        $url=$first.$artist.$second.$album;
        
        $html=  file_get_contents($url,true);
        $json=  json_decode($html,true);
        if(isset($json['error'])){
            if($json['error']==6){
                return;
            }
        }
	$tracks=array();
	$array=$json['album']['tracks']['track'];
        //if the name is not set, it means that there is only 0 or 1 track for the given album name
        if(!isset($array['name'])){
            for($i=0; $i<count($array); $i++){
                $newtrack=new Track();
                $newtrack->setName($array[$i]['name']);
                array_push($tracks,$newtrack);
            }
        }
        else{
            $newtrack=new Track();
            $newtrack->setName($array['name']);
            $youtube=$this->playerLink($artistName,$array['name']);
            if($youtube==null){
                return $tracks;
            }
            $newtrack->setYoutube($youtube);
            array_push($tracks,$newtrack);
        }
	return ($tracks);
    }
    
    /**
     * Retrieves all the albums that belong to an artist from last.fm
     * @param String $artistName The artist name
     * @return array of albums
     */
    public function getAlbumsFromWeb($artistName){

        $listAlbum=array();
        $first='http://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&format=json&artist=';
        $key='&api_key=2e0f6a31b6598dae0585ac68964d579c';
        $artistName=str_replace(' ', '%20', $artistName);
        $url=$first.$artistName.$key;
	
	$html=file_get_contents($url,true);
        $json=  json_decode($html,true);
        $albumname='';
     	$albumcoverlink='';
        if(!isset($json['topalbums'])){
            return null;
        }
        $array=$json['topalbums']['album'];
        $albumname=array();
    	foreach($array as $item){
    		$newAlbum=new Album();
    		$newAlbum->setName($item['name']);
    		$newAlbum->setCover($item['image'][3]['#text']);
    		array_push($listAlbum,$newAlbum);	
	}
        //retrieve the amount of pages
	$page=$json['topalbums']['@attr']['totalPages'];
	//call each page
	for ($i = 2; $i <=$page; $i++) {	
            $first='http://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&format=json&page='.$i.'&artist=';
            $key='&api_key=2e0f6a31b6598dae0585ac68964d579c';

            $url=$first.$artistName.$key;

            $html=  file_get_contents($url,true);
            $json=  json_decode($html,true);
            $array=$json['topalbums']['album'];
            foreach($array as $item){
		$newAlbum=new Album();
		$newAlbum->setName($item['name']);
                if(isset($item['image'])){
                    $newAlbum->setCover($item['image'][3]['#text']);
                }
                else{
                    //default cover
                    $newAlbum->setCover('http://image.spreadshirt.com/image-server/image/composition/2482662/view/1/producttypecolor/2/type/png/width/280/height/280/unknown-album-t-shirt_design.png');
                }
		array_push($listAlbum,$newAlbum);		
            }   
        }
        return $listAlbum;
    }

    /**
     * Retrieves an artist image from last.fm
     * @param String $artist The artist name
     * @return String a link to an artist image 
     */
    public function getArtistCover($artist){
        $first='http://ws.audioscrobbler.com/2.0/?method=artist.getimages&format=json&artist=';
        $key='&api_key=2e0f6a31b6598dae0585ac68964d579c';
        $artist=str_replace(' ','%20',$artist);
        $url=$first.$artist.$key;
        $html=  file_get_contents($url,true);
        $json=  json_decode($html,true);
        $cover = $json['images']['image'][0]['sizes']['size'][0]['#text'];
        return $cover;

    }
	
    /**
     * Retrieves the artist bio from last.fm
     * @param String $artist the artist name
     * @return String the artist bio 
     */
    public function getArtistBio($artist){
        $first='http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&format=json&artist=';
        $key='&api_key=2e0f6a31b6598dae0585ac68964d579c';
        $artist=str_replace(' ','%20',$artist);
        $url=$first.$artist.$key;	
        $html=  file_get_contents($url,true);
        $json=  json_decode($html,true);
        $info = $json['artist']['bio']['content'];

        return $info;
    }

    /**
     * Retrieves an artist image and the bio from last fm
     * @param String $artist The artist name
     * @return array Where the first element is the cover and the second element is the bio
     */
    public function getArtistInfo($artist){
        $first='http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&format=json&artist=';
        $key='&api_key=2e0f6a31b6598dae0585ac68964d579c';
        $artist=str_replace(' ','%20',$artist);
        $url=$first.$artist.$key;	
        $html=  file_get_contents($url,true);
        $json=  json_decode($html,true);
        $info = $json['artist']['bio']['content'];
        $covers=$json['artist']['image'];
        $cover=$covers[count($covers)-1]['#text'];
        $out=array();
        array_push($out,$cover);
        array_push($out,$info);

        return $out;
    }

    /**
     * Retrieves the release info of an album
     * @param String $artist The artist name
     * @param String $album The album name
     * @return string The release info of the album
     */
    function getAlbumInfo($artist, $album){
        $first='http://ws.audioscrobbler.com/2.0/?method=album.getinfo&format=json&artist=';
        $key='&api_key=2e0f6a31b6598dae0585ac68964d579c';
        $artist=str_replace(' ','%20',$artist);
        $tussen='&album=';
        $album=str_replace(' ','%20',$album);
        $url=$first.$artist.$tussen.$album.$key;
        $html=  file_get_contents($url,true);
        $json=  json_decode($html,true);

        $info; 

        if(isset($json['album']['wiki'])){	
        if($json['album']['wiki']['content'] != ""){
            $info = $json['album']['wiki']['content'];
        }else if($json['album']['wiki']['summary'] != ""){
            $info = $json['album']['wiki']['summary'];
        }
        }
        else {
            $info = 'Sorry, we don\'t have any information about this album';
        }
            return $info;

    }

    /**
     * Retrieves all the track of an artist (max 1000)
     * @param String $artistName The artist name
     * @return array of tracks
     */
    function getTopTracks($artistName)
    {
        $first='http://ws.audioscrobbler.com/2.0/?method=artist.gettoptracks&format=json&artist=';
        $key='&api_key=2e0f6a31b6598dae0585ac68964d579c';
        $artist=str_replace(' ','%20',$artistName);
        $url=$first.$artist.$key;
        $html=file_get_contents($url,true);
        $json=json_decode($html,true);
        $listTracks=array();
        //get the amount of pages
        $totalPages=(int)$json['toptracks']['@attr']['totalPages'];

        //retrieve each page
        for($i=0;$i<=$totalPages;$i++)
        {
            
            $first='http://ws.audioscrobbler.com/2.0/?method=artist.gettoptracks&format=json&page='.$i.'&artist=';
            $key='&api_key=2e0f6a31b6598dae0585ac68964d579c';
            $url=$first.$artist.$key;
            $html=file_get_contents($url,true);
            $json=json_decode($html,true);

            if(isset($json['toptracks']['track']))
            {
                $array=$json['toptracks']['track'];
                foreach($array as $key=>$object)
                {
                    $track=new Track();
                    $track->setName($object['name']);
                    array_push($listTracks,$track);
                }
            }
        }
        return $listTracks;
    }
    
}
?>
